$(document).ready(function(){
    page(1);
});

function updateBooksView(books){
    var table=$("<table class='table_book'></table>");
    $("#bookView").empty();
        var title=$("<tr><th>ID</th><th>图片</th><th>书名</th><th>作者</th><th>梗概</th><th>价格</th><th></th><th></th></tr>");
        table.append(title);
        for(var book of books){
            var tr=$("<tr></tr>");
            tr.append("<td>"+book.id+"</td>");
            tr.append("<td>"+"<img class='book-img' src='./images/upload/"+book.picture+"'>"+"</td>");
            tr.append("<td>"+book.name+"</td>");
            tr.append("<td>"+book.author+"</td>");
            tr.append("<td>"+book.content+"</td>");
            tr.append("<td>"+book.price+"</td>");
            tr.append("<td><a href='./DeleteBook?bookId="+book.id+"' style='color:black'>删除</a></td>");
            tr.append("<td><a href='./update.html?bookId="+book.id+"' style='color:black'>修改</a></td>");
            table.append(tr);
        }
    $("#bookView").append(table);
}

function findByPage(curPage){
    $("li[name='liPage']").remove();
    page(curPage);
}

function leftQuery(){
    var curPage=$("li[class='active']").text();
    if(curPage==1) return;
    findByPage(parseInt(curPage)-1);
}

function rightQuery(){
    var curPage=$("li[class='active']").text();
    if(curPage==(($("li").length)-2)) return;
    findByPage(parseInt(curPage)+1);
}

function page(curPage){
    $.get(
    "queryPage",
    "page="+curPage,
    function(data){
        updateBooksView(data.books);

        for(var i=0;i<data.totalPages;i++){
            var $li=$("<li name='liPage'><a href='#' onclick='findByPage($(this).html())'>"+(i+1)+"</a></li>");
            $li.append("\xa0\xa0");
            $("li:last").before($li);
            if(data.curPage==(i+1)){
                $li.attr("class","active");
            }
        }
    },
    "json"
    );
}
